package com.uvnos4j.matilda.system.controller;

import com.uvnos4j.matilda.commons.annotation.AppLog;
import com.uvnos4j.matilda.commons.dto.Result;
import com.uvnos4j.matilda.system.domain.SysAcl;
import com.uvnos4j.matilda.system.domain.SysUser;
import com.uvnos4j.matilda.system.service.SysAuthService;
import com.uvnos4j.matilda.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统授权控制器
 * <p>
 * Description:
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.system.controller
 * @since 2020-08-31 23:12:33
 */
@Controller
@RequestMapping("/sys/auth")
public class SysAuthController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysAuthService sysAuthService;

    @AppLog(title = "授权管理")
    @PreAuthorize("hasAuthority('sys:auth')")
    @GetMapping
    public String index() {
        return "sys/auth";
    }

    @PreAuthorize("hasAuthority('sys:auth')")
    @GetMapping("/aclTree")
    @ResponseBody
    public Result roleTree(@RequestParam("roleId") Long roleId) {
        SysUser user = sysUserService.getUserInfo();
        List<SysAcl> treeNodes = sysAuthService.buildRoleAclTree(user, roleId);
        return Result.success(treeNodes);
    }

    @PreAuthorize("hasAuthority('sys:auth')")
    @GetMapping("/userList")
    @ResponseBody
    public Result userList(@RequestParam("roleId") Long roleId) {
        List<SysUser> roleUserList = sysAuthService.findRoleUserList(roleId);
        List<SysUser> roleNoUserList = sysAuthService.findRoleNoUserList(roleId);
        Map<String, Object> data = new HashMap<>(16);
        data.put("select", roleUserList);
        data.put("unselect", roleNoUserList);
        return Result.success(data);
    }

    @AppLog(title = "授权-保存权限")
    @PreAuthorize("hasAuthority('sys:auth:saveAcl')")
    @PostMapping("/saveAcls")
    @ResponseBody
    public Result saveAcls(@RequestParam("roleId") Long roleId, @RequestParam("aclIds") List<Long> aclIdList) {
        sysAuthService.saveRoleAcls(roleId, aclIdList);
        return Result.success("角色权限保存成功");
    }

    @AppLog(title = "授权-保存用户")
    @PreAuthorize("hasAuthority('sys:auth:saveUser')")
    @PostMapping("/saveUsers")
    @ResponseBody
    public Result saveUsers(@RequestParam("roleId") Long roleId, @RequestParam("userIds") List<Long> userIdList) {
        sysAuthService.saveRoleUsers(roleId, userIdList);
        return Result.success("角色用户保存成功");
    }

}